import { getAddressData, addAddress, addressInfoData, delAddress, editAddress, defaultAddress } from 'api/address'

export default {
  namespaced: true,
  state: {
    address: []
  },
  mutations: {
    ['SET_ADDRESS'] (state, payload) {
      state.address = payload.address
    },
    ['DEL_ADDRESS'] (state, payload) {
      state.address.splice(payload.index, 1)
    },
    ['ADD_ADDRESS'] (state, payload) {
      state.address.push(payload.address)
    },
  },
  actions: {
    // 获取收货地址
    getAddress (context) {
      getAddressData(context.rootState.user.uid).then(res => {
        if (res.code === 200) {
          context.commit('SET_ADDRESS', { address: res.data })
        }else{
          context.commit('SET_ADDRESS', { address: [] })
        }
      })
    },
    // 收货地址详细内容
    addressInfo (context, payload) {
      addressInfoData({ uid: context.rootState.user.uid, aid: payload.aid }).then(res => {
        payload.success && payload.success(res)
      })
    },
    // 删除地址
    delAddress (context, payload) {
      delAddress({ uid: context.rootState.user.uid, aid: payload.aid }).then(res => {
        if (res.code === 200) {
          context.commit('DEL_ADDRESS', { index: payload.index })
        }
        payload && payload.success(res)
      })
    },
    // 添加收货地址
    addAddress (context, payload) {
      return addAddress({
        uid: context.rootState.user.uid,
        ...payload
      }).then(res => {
        if (res.code === 200) {
          context.commit('ADD_ADDRESS', { address: res.data })
        }
        return res
      })
    },
    // 修改收货地址
    editAddress (context, payload) {
      return editAddress({
        uid: context.rootState.user.uid,
        ...payload
      }).then(res => res)
    },
    // 默认收货地址
    defaultAddress (context) {
      return defaultAddress(context.rootState.user.uid).then(res => res)
    }
  }
}
